<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Category;
use App\Post;
use App\Tag;
use Session;
use Purifier;

class PostController extends Controller
{
    /**
     * 帖子操作必须是登录用户
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::orderby('id', 'desc')->paginate(10);
        return view('post.index')->withPosts($posts);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $cats = array();
        $categories = Category::all();
        foreach ($categories as $category) {
            $cats[$category->id] = $category->name;
        }

        $tags = array();
        $tagList = Tag::all();
        foreach ($tagList as $tag) {
            $tags[$tag->id] = $tag->name;
        }

        return view('post.create')->withCategories($cats)->withTags($tags);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'title'=>'required|max:255',
            'slug'=>'required|min:5|max:255|alpha_dash|unique:posts,slug',
            'category_id'=>'required',
            'body'=>'required'
        ], [
            'required'=>':attribute 不能为空',
            'max'=>':attribute 不能超过 :max',
            'min'=>':attribute 不得少于 :min 字符',
            'alpha_dash'=>'Slug 格式不正确,只能含字母、数字、破折号（ - ）以及下划线（ _ ）',
            'unique'=>'Slug 不是唯一的'
        ]);

        $post = new Post();
        $post->title = $request->title;
        $post->body  = Purifier::clean($request->body);
        $post->slug  = $request->slug;
        $post->category_id = $request->category_id;
        $post->save();

        $post->tag()->sync($request->tag, false);

        Session::flash('success', '博文发布成功');
        return redirect()->route('post.show', $post);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Post::find($id);
        return view('post.show')->withPost($post);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $cats = array();
        $post = Post::find($id);
        $categories = Category::all();
        foreach ($categories as $category) {
            $cats[$category->id] = $category->name;
        }
        $tags = array();
        $tagList = Tag::all();
        foreach ($tagList as $tag) {
            $tags[$tag->id] = $tag->name;
        }

        return view('post.edit')->withPost($post)
            ->withCategories($cats)->withTags($tags);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $msg = [
            'title.required'=>'标题不能为空',
            'title.max'=>'标题 不能超过: :max',
            'body.required'=>'内容不能为空',
            'slug.min'=>'Slug 不得少于: :min 字符',
            'slug.max'=>'Slug 不能超过: :max 字符',
            'slug.unique'=>'Slug 不是唯一的',
            'slug.alpha_dash'=>'Slug 格式不正确,只能含字母、数字、破折号（ - ）以及下划线（ _ ）'
        ];

        $post = Post::find($id);
        if ($request->slug == $post->slug) {
            $this->validate($request, [
                'title'=>'required|max:255',
                'slug'=>'required|min:5|max:255|alpha_dash',
                'body'=>'required'
            ], $msg);
        } else {
            $this->validate($request, [
                'title'=>'required|max:255',
                'slug'=>'required|min:5|max:255|alpha_dash|unique:posts,slug',
                'body'=>'required'
            ], $msg);
        }

        $post->title = $request->title;
        $post->body  = Purifier::clean($request->body);
        $post->slug  = $request->slug;
        $post->category_id = $request->category_id;
        $post->save();

        if (empty($request->tag)) {
            $post->tag()->sync(array());
        }else{
            $post->tag()->sync($request->tag);
        }

        Session::flash('success', '博文修改成功');
        return redirect()->route('post.show', $post->id);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $post = Post::find($id);
        $post->tag()->detach();
        $post->delete();
        return redirect()->route('post.index');
    }
}
